// game.js - 微信小程序游戏文件
import Main from './js/main'

// 检查环境类型
const isGameSubContext = typeof GameGlobal !== 'undefined' && GameGlobal.IS_GAME_SUB_CONTEXT;
const isPageContext = typeof Page !== 'undefined';

console.log('环境检测:', {
  isGameSubContext,
  isPageContext,
  hasWx: typeof wx !== 'undefined',
  hasGameGlobal: typeof GameGlobal !== 'undefined'
});

// 全局游戏实例
let gameInstance = null;

// 处理分享进入
function handleShareEntry(options) {
  console.log('处理分享进入:', options);
  
  if (options && options.roomId) {
    console.log('检测到房间邀请:', options.roomId);
    
    // 延迟处理，确保游戏已初始化
    setTimeout(() => {
      if (gameInstance) {
        // 自动加入房间
        const onlineMenu = gameInstance.getOnlineMenu();
        if (onlineMenu) {
          onlineMenu.autoJoinRoom(options.roomId);
        }
      }
    }, 1000);
  }
}

// 设置分享功能
function setupShareFeatures() {
  if (typeof wx !== 'undefined') {
    // 设置分享到聊天
    wx.onShareAppMessage(() => {
      if (gameInstance) {
        const onlineMenu = gameInstance.getOnlineMenu();
        if (onlineMenu) {
          const shareInfo = onlineMenu.getShareInfo();
          if (shareInfo) {
            return shareInfo;
          }
        }
      }
      
      return {
        title: '五子棋 - 经典对战游戏',
        path: '/pages/game',
        imageUrl: '/images/share.jpg'
      };
    });
    
    // 设置分享到朋友圈
    wx.onShareTimeline(() => {
      if (gameInstance) {
        const onlineMenu = gameInstance.getOnlineMenu();
        if (onlineMenu) {
          const shareInfo = onlineMenu.getShareInfo();
          if (shareInfo && shareInfo.query) {
            return {
              title: shareInfo.title,
              query: shareInfo.query,
              imageUrl: shareInfo.imageUrl
            };
          }
        }
      }
      
      return {
        title: '五子棋 - 经典对战游戏',
        query: '',
        imageUrl: '/images/share.jpg'
      };
    });
  }
}

// 游戏初始化函数
function initGame() {
  try {
    console.log('开始初始化游戏...');
    
    // 创建Canvas
    const canvas = wx.createCanvas();
    const ctx = canvas.getContext('2d');
    
    // 设置Canvas尺寸
    const systemInfo = wx.getSystemInfoSync();
    const screenWidth = systemInfo.screenWidth;
    const screenHeight = systemInfo.screenHeight;
    const pixelRatio = systemInfo.pixelRatio || 1;
    
    canvas.width = screenWidth * pixelRatio;
    canvas.height = screenHeight * pixelRatio;
    ctx.scale(pixelRatio, pixelRatio);
    
    console.log('Canvas初始化成功:', {
      width: canvas.width,
      height: canvas.height,
      pixelRatio: pixelRatio
    });
    
    // 设置全局Canvas
    if (typeof GameGlobal !== 'undefined') {
      GameGlobal.canvas = canvas;
    }
    
    // 创建游戏实例
    gameInstance = new Main(canvas, ctx);
    
    // 设置触摸事件
    setupTouchEvents(canvas, gameInstance);
    
    // 设置分享功能
    setupShareFeatures();
    
    console.log('游戏初始化完成');
    
    return gameInstance;
  } catch (error) {
    console.error('游戏初始化失败:', error);
    showError('游戏启动失败，请重试');
    return null;
  }
}

// 设置触摸事件
function setupTouchEvents(canvas, gameInstance) {
  if (!canvas || !gameInstance) return;
  
  try {
    // 检查Canvas是否支持addEventListener
    if (typeof canvas.addEventListener === 'function') {
      // 使用标准的addEventListener方法
      canvas.addEventListener('touchstart', (e) => {
        e.preventDefault();
        if (gameInstance.handleTouch) {
          const touch = e.touches[0];
          const rect = canvas.getBoundingClientRect();
          const x = touch.clientX - rect.left;
          const y = touch.clientY - rect.top;
          gameInstance.handleTouch(x, y);
        }
      });
      
      canvas.addEventListener('touchmove', (e) => {
        e.preventDefault();
      });
      
      canvas.addEventListener('touchend', (e) => {
        e.preventDefault();
      });
      
      console.log('使用标准addEventListener设置触摸事件');
    } else {
      // 使用微信小游戏的触摸事件API
      console.log('使用微信小游戏触摸事件API');
      
      // 监听触摸开始事件
      wx.onTouchStart((e) => {
        if (gameInstance.handleTouch && e.touches && e.touches.length > 0) {
          const touch = e.touches[0];
          const x = touch.clientX;
          const y = touch.clientY;
          gameInstance.handleTouch(x, y);
        }
      });
      
      // 监听触摸移动事件
      wx.onTouchMove((e) => {
        // 防止页面滚动
      });
      
      // 监听触摸结束事件
      wx.onTouchEnd((e) => {
        // 触摸结束处理
      });
      
      console.log('使用wx.onTouchStart设置触摸事件');
    }
  } catch (error) {
    console.error('设置触摸事件失败:', error);
    // 尝试使用wx.onTouchStart作为备选方案
    try {
      wx.onTouchStart((e) => {
        if (gameInstance.handleTouch && e.touches && e.touches.length > 0) {
          const touch = e.touches[0];
          const x = touch.clientX;
          const y = touch.clientY;
          gameInstance.handleTouch(x, y);
        }
      });
      console.log('使用备选方案设置触摸事件');
    } catch (fallbackError) {
      console.error('备选方案也失败:', fallbackError);
    }
  }
}

// 显示错误信息
function showError(message) {
  try {
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 3000
    });
  } catch (error) {
    console.error('显示错误提示失败:', error);
  }
}

// 页面环境下的处理
if (isPageContext) {
  console.log('使用页面环境');
  
  Page({
    data: {
      // 页面数据
    },

    onLoad: function (options) {
      console.log('页面加载完成');
      handleShareEntry(options); // 处理分享进入
    },

    onReady: function () {
      console.log('页面渲染完成');
      
      // 延迟初始化Canvas，确保DOM已经渲染完成
      setTimeout(() => {
        this.initCanvas();
      }, 100);
    },

    onShow: function () {
      console.log('页面显示');
    },

    onHide: function () {
      console.log('页面隐藏');
    },

    onUnload: function () {
      console.log('页面卸载');
      // 清理游戏实例
      if (this.gameInstance) {
        this.gameInstance = null;
      }
    },

    // 分享到聊天
    onShareAppMessage: function () {
      if (this.gameInstance) {
        const onlineMenu = this.gameInstance.getOnlineMenu();
        if (onlineMenu) {
          const shareInfo = onlineMenu.getShareInfo();
          if (shareInfo) {
            return shareInfo;
          }
        }
      }
      
      return {
        title: '五子棋 - 经典对战游戏',
        path: '/pages/game',
        imageUrl: '/images/share.jpg'
      };
    },

    // 分享到朋友圈
    onShareTimeline: function () {
      if (this.gameInstance) {
        const onlineMenu = this.gameInstance.getOnlineMenu();
        if (onlineMenu) {
          const shareInfo = onlineMenu.getShareInfo();
          if (shareInfo && shareInfo.query) {
            return {
              title: shareInfo.title,
              query: shareInfo.query,
              imageUrl: shareInfo.imageUrl
            };
          }
        }
      }
      
      return {
        title: '五子棋 - 经典对战游戏',
        query: '',
        imageUrl: '/images/share.jpg'
      };
    },

    // 页面触摸事件处理
    onTouchStart: function (e) {
      if (this.gameInstance && this.gameInstance.handleTouch) {
        const touch = e.touches[0];
        const x = touch.clientX;
        const y = touch.clientY;
        this.gameInstance.handleTouch(x, y);
      }
    },

    onTouchMove: function (e) {
      // 防止页面滚动
      e.preventDefault();
    },

    onTouchEnd: function (e) {
      // 触摸结束处理
    },

    initCanvas: function () {
      try {
        console.log('开始初始化Canvas...');
        
        // 获取Canvas上下文
        const query = wx.createSelectorQuery();
        query.select('#canvas')
          .fields({ node: true, size: true })
          .exec((res) => {
            if (res && res[0] && res[0].node) {
              const canvas = res[0].node;
              const ctx = canvas.getContext('2d');
              
              // 设置Canvas尺寸 - 使用新的API获取像素比
              let dpr = 1;
              try {
                if (wx.getDeviceInfo) {
                  const deviceInfo = wx.getDeviceInfo();
                  dpr = deviceInfo.pixelRatio || 1;
                } else if (wx.getSystemInfoSync) {
                  const systemInfo = wx.getSystemInfoSync();
                  dpr = systemInfo.pixelRatio || 1;
                }
              } catch (error) {
                console.warn('获取像素比失败，使用默认值:', error);
                dpr = 1;
              }
              
              // 确保Canvas尺寸正确设置
              const canvasWidth = res[0].width || 375;
              const canvasHeight = res[0].height || 667;
              
              canvas.width = canvasWidth * dpr;
              canvas.height = canvasHeight * dpr;
              ctx.scale(dpr, dpr);
              
              console.log('Canvas初始化成功:', {
                width: canvas.width,
                height: canvas.height,
                dpr: dpr,
                originalWidth: canvasWidth,
                originalHeight: canvasHeight
              });
              
              // 将Canvas传递给游戏
              this.initGame(canvas, ctx);
            } else {
              console.error('Canvas节点获取失败');
              this.showError('Canvas初始化失败，请重试');
            }
          });
      } catch (error) {
        console.error('Canvas初始化失败:', error);
        this.showError('Canvas初始化失败，请重试');
      }
    },

    initGame: function (canvas, ctx) {
      try {
        console.log('开始初始化游戏...');
        
        // 设置全局Canvas
        if (typeof GameGlobal !== 'undefined') {
          GameGlobal.canvas = canvas;
        }
        
        // 创建游戏实例
        this.gameInstance = new Main(canvas, ctx);
        
        console.log('游戏初始化完成');
      } catch (error) {
        console.error('游戏初始化失败:', error);
        this.showError('游戏启动失败，请重试');
      }
    },

    showError: function (message) {
      try {
        wx.showToast({
          title: message,
          icon: 'none',
          duration: 3000
        });
      } catch (error) {
        console.error('显示错误提示失败:', error);
      }
    }
  });
} else {
  // 游戏子包环境下的处理
  console.log('使用游戏子包环境');
  
  // 延迟初始化，确保环境完全加载
  setTimeout(() => {
    initGame();
  }, 100);
}
